-- UICombatStat
-- Create by panyl Jan/7/2015
-- 战斗统计界面

require "game/ui/form/share/UIShareSelect";

-- UICombatStat继承自Layer
UICombatStat = class("UICombatStat", function()
    return cc.Layer:create();
end);

function UICombatStat.create(combatStat, dungeonId)
    return UICombatStat.new(combatStat, dungeonId);
end

local STAT_STATE_TITLE_ANIMA   =    1;
local STAT_STATE_SCORE_ANIM    =    2;
local STAT_STATE_GROUP1_ANIM   =    3;
local STAT_STATE_GROUP4_ANIM   =    4;
local STAT_STATE_EXP_ANIM      =    5;
local STAT_STATE_END           =    6;

-- 内部函数声明
local resize;

-- 加速因子
local accelarateFactor = 1;

-- 每页停留时间
local waitingTime = 4;

-- 第一组和第二组数据飞入时间
local textDuration = 0.3;

-- 构造函数
function UICombatStat:ctor(combatStat, dungeonId)
    -- 初始化
    self:setName("UICombatStat");
    local node = cc.CSLoader:createNode("layout/combat_stat/CombatStat.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 地牢ID
    if dungeonId ~= nil then
        self.dungeonId = dungeonId;
    end

    -- 战斗统计信息
    self.combatStat = combatStat;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 初始化
    self:init();

    -- 开始动画效果
    self:start();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "black_bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- top_bg置于顶部
    AlignM.alignToTopCenter(node, "top_bg");
    AlignM.alignToTopCenter(node, "TOP");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
    AlignM.alignToBottomCenter(node, "bottom_bg");

    local TOP = node:getChildByName("TOP");
    local scale = math.max(w / DESIGN_WIDTH, h / DESIGN_HEIGHT);

    local topBg = findChildByName(node, "top_bg");
    local bottomBg = findChildByName(node, "bottom_bg");

    -- 上下底图的大小为640所以这么处理
    if h / w < 1.5 then
        topBg:setScaleX(768/DESIGN_WIDTH * topBg:getScale());
        bottomBg:setScaleX(768/DESIGN_WIDTH * bottomBg:getScale());
        scale = 768/DESIGN_WIDTH * bottomBg:getScaleX();
    end

    bottomBg:setPosition(w/2, -40 * scale);
end

-- 分享成功的处理
function UICombatStat:whenShareSucc()
    -- 隐藏冒泡
    local btnShare = findChildByName(self.node, "BT/btn_share");
    local hintNode = findChildByName(btnShare, "hint");
    checkBlueBubbleStatus(hintNode, false);
    setButtonEnabled(btnShare, false);
end

-- 注册事件处理回调函数
function UICombatStat:registerEventCallback()
    -- 注册迷宫通关结果的事件回调
    EventMgr.register("UICombatStat", event.RECV_DUNGEON_RESULT, function(args)
        self.shareArgs = args;

        self:redrawShareButton();
    end);

    -- 注册facebook分享成功的事件
    EventMgr.register("UICombatStat", event.FB_SHARE_SUCC, function(args)
        self:whenShareSucc();
    end);

    -- 注册line分享成功的事件
    EventMgr.register("UICombatStat", event.LINE_SHARE_SUCC, function(args)
        self:whenShareSucc();
    end);

    -- 关注微信分享成功事件
    EventMgr.register("UICombatStat", event.WECHAT_SHARE_SUCC, function(args)
        self:whenShareSucc();
    end);

    -- 关注微博分享成功事件
    EventMgr.register("UICombatStat", event.WEIBO_SHARE_SUCC,  function(args)
        self:whenShareSucc();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UICombatStat 界面析构清理");
            EventMgr.removeAll("UICombatStat");
            EventMgr.fire(event.USER_INFO_UPDATED);
            if UIDungeonMgr:getCurLevel() ~= nil then
                UIDungeonMgr:getCurLevel():hideTop();
            end
        elseif ev == "enter" then

        end
    end);
end

-- 显示分享界面
function UICombatStat:showShareForm()
    if not self.shareArgs then
        -- 没有触发分享，不处理
        trace("UICombatStat", "没有触发分享。");
        return;
    end

    local args      = self.shareArgs;
    local dungeonId = args.dungeonId;
    local layer     = args.layer;
    local score     = args.score;
    local defeatPercent  = args.defeatPercent;
    local championNation = args.championNation;  -- 第一名玩家国籍

    if isShareFuncOpen() then
        local areaName = DungeonAreaM.query(dungeonId, "name")
        local shareTitle = string.format(getLocStr("fb_dungeon_share_title"), areaName);
        local shareContent = "";

        if isOverseaPackage() then
            -- 海外版本
            if type(championNation) == 'number' and championNation ~= 0 then
                local nationName = TopM.queryNationality(championNation, "full_name");
                shareContent = string.format(getLocStr("fb_dungeon_share_content"), layer, defeatPercent, nationName);
            else
                shareContent = string.format(getLocStr("fb_dungeon_share_content2"), layer, defeatPercent);
            end
        else
            -- 国内版本
            shareContent = getLocStr("cn_dungeon_share_content");
            shareContent = string.gsub(shareContent, "{area_name}", areaName);
            shareContent = string.gsub(shareContent, "{layer}", layer);
        end

        local extra = { ["title"] = shareTitle, ["desc"] = shareContent };

        local title   = getLocStr("dungeon_share_title");
        local content = getLocStr("dungeon_share_content");

        showShareForm(SHARE_TYPE_DUNGEON, title, content, extra);
    end
end

-- 重绘
function UICombatStat:redraw()
    local node = self.node;

    -- 标题部分
    local formTitleLabel = findChildByName(node, "TOP/title_node/title");
    formTitleLabel:setString(getLocStr("dungeon_stat_title"));
    TextStyleM.setArtWordTitleStyle(formTitleLabel);

    -- TOP/BOTTOM背景
    local topBg = findChildByName(node, "top_bg");
    local bottomBg = findChildByName(node, "bottom_bg");

    -- 根据地图区域获取风格
    local dungeonId = DungeonM.getDungeonId()
        or self.dungeonId or ME.user.dbase:query("currentDungeon");
    self.dungeonId = dungeonId;

    local parentId;
    if dungeonId ~= nil then
        parentId  = DungeonAreaM.getParentId(dungeonId);
    end

    -- 设置顶部和底部背景
    -- 如果没有配置上下底图标，默认使用关卡编号
    local topBottomIcon = DungeonAreaM.query(parentId, "top_bottom_icon");
    if topBottomIcon == "" or topBottomIcon == nil then
        topBottomIcon = parentId;
    end

    local path = "images/ui/level/cover/";
    if parentId ~= nil then
        local topBgPath = path .. "top/" .. topBottomIcon .. ".png";
        local bottomBgPath = path .. "bottom/" .. topBottomIcon .. ".png";
        topBg:loadTexture(topBgPath);
        bottomBg:loadTexture(bottomBgPath);
    else
        topBg:setVisible(false);
        bottomBg:setVisible(false);
    end

    -- CT部分
    -- GROUP1/panel部分
    local group1 = findChildByName(node, "CT/group1");
    local panel = findChildByName(node, "CT/panel");
    group1:setAnchorPoint(cc.p(0, 0));
    panel:setAnchorPoint(cc.p(0.5, 0.5));
    local panelItems = findChildByName(node, "CT/panel/items");
    -- 先设成不可拖动
    panelItems:setTouchEnabled(false);

    local kerning = 0;
    if not isFullWidthLang() then
        kerning = -2;
    end

    -- BT部分
    -- 载入文字资源
    local goldTitle = findChildByName(node,"BT/gold_node/left/gold_title");
    local expTitle = findChildByName(node,"BT/exp_node/left/exp_title");
    local expProgressTitle = findChildByName(node,"BT/exp_progress_node/left/exp_progress_title");
    local goldStr = getLocStr("get_gold_coin");
    local expStr = getLocStr("get_exp");
    local expProgressStr = getLocStr("exp_progress");
    TextStyleM.setTextStyle(goldTitle, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true, kerning, nil, nil, nil, nil, nil, TextStyleM.getTextScale(goldStr, 12));
    TextStyleM.setTextStyle(expTitle, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true, kerning, nil, nil, nil, nil, nil, TextStyleM.getTextScale(expStr, 12));
    TextStyleM.setTextStyle(expProgressTitle, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true, kerning, nil, nil, nil, nil, nil, TextStyleM.getTextScale(expProgressStr, 10));
    goldTitle:setString(goldStr);
    expTitle:setString(expStr);
    expProgressTitle:setString(expProgressStr);

    -- 设置第一组数据
    for i = 1, 12 do
        local id = i;
        local title;
        local score;
        local titleStr;

        if (CombatStatM.query(id, "join")) == 1 then
            local item = findChildByName(self.node, "CT/group1/item"..i);
            title = item:getChildByName("text");
            score = item:getChildByName("score");
            score.statData = CombatStatM.getProgress(id);

            titleStr = CombatStatM.query(id, "desc");
            TextStyleM.setTextStyle(title, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true, kerning, nil, nil, nil, nil, nil, TextStyleM.getTextScale(titleStr, 16));
            TextStyleM.setTextStyle(score, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true);
            title:setString(titleStr);
            score:setString(tostring(score.statData));
        end
    end

    local attribScore = 0;

    -- 设置第二组数据（属性/称号/宝物）
    for i = 13, 15 do
        local id = i;
        local item = findChildByName(self.node, "CT/group1/item"..i);
        local score = item:getChildByName("score");
        local title = item:getChildByName("text");

        TextStyleM.setTextStyle(title, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true, kerning);
        TextStyleM.setTextStyle(score, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE, true);
        if i == 13 then
            score.statData = self.combatStat.score2;
            title:setString(getLocStr("attrib_stat"));
            score:setString(tostring(self.combatStat.score2));
        elseif i == 14 then
            score.statData = self.combatStat.score3;
            title:setString(getLocStr("skill_stat"));
            score:setString(tostring(self.combatStat.score3));
        else
            title:setString(getLocStr("equip_stat"));
            score.statData = self.combatStat.score4;
            score:setString(tostring(self.combatStat.score4));
        end

    end

    -- 总评分
    local titleSumLabel = findChildByName(self.node, "BT/total_score_node/title_sum");
    local scoreSumLabel = findChildByName(self.node, "BT/total_score_node/score_sum");
    TextStyleM.setTextStyle(titleSumLabel, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, kerning);
    TextStyleM.setTextStyle(scoreSumLabel, TextStyleM.TEXT_SIZE_LARGE, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true);
    titleSumLabel:setString(string.format(getLocStr("get_scores") .. tostring(self.combatStat.sum)));
    scoreSumLabel.statData = self.combatStat.sum;
    titleSumLabel:setAnchorPoint(cc.p(0.5, 0));
    scoreSumLabel:setAnchorPoint(cc.p(0.5, 0));
    scoreSumLabel:setVisible(false);

    -- 先设置为0
    scoreSumLabel:setString("0");

    -- 先显示老的进度
    local loadingBar = findChildByName(self.node, "BT/exp_progress_node/right/progress_bg/loading_bar");

    if not ME.user.oriExpInfo then
        ME.user.oriExpInfo = {
            ["exp"] = ME.user:getExp(),
            ["level"] = ME.user:getLevel(),
        };
    end

    self.curExp = ME.user.oriExpInfo["exp"];
    self.curLevel = ME.user.oriExpInfo["level"];
    self.curMaxExp = UserM.queryWorldTree(self.curLevel, "exp");
    print("UICombatStat 当前经验：" .. self.curExp .. ",最大经验：" .. self.curMaxExp);
    local percent = self.curExp / self.curMaxExp * 100;
    loadingBar:setPercent(percent);

    -- 进度条
    self.playingLevelUpEffect = false;
    self.waitUserClick = false;

    -- 奖励
    local bonus = self.combatStat.bonus;
    self.totalMoney = 0;
    self.totalExp = 0;

    for _, info in pairs(bonus) do
        if info[2] == "money" then
            self.totalMoney = info[3];
        elseif info[2] == "exp" then
            self.totalExp = info[3];
        end
    end

    -- 计算升级
    self.finalLevel = self.curLevel;
    self.finalExp = self.curExp + self.totalExp;
    local MaxExp = UserM.queryWorldTree(self.finalLevel, "exp");
    while self.finalLevel < MAX_USER_LEVEL and self.finalExp >= MaxExp do
        self.finalLevel = self.finalLevel + 1;
        self.finalExp = self.finalExp - MaxExp;
        MaxExp = UserM.queryWorldTree(self.finalLevel, "exp");
    end
    if self.finalLevel == MAX_USER_LEVEL and
       self.finalExp > UserM.queryWorldTree(self.finalLevel, "exp") then
        -- 经验爆了，修正一下
        self.finalExp = UserM.queryWorldTree(self.finalLevel, "exp");
    end

    -- 重绘分享按钮
    self:redrawShareButton();
end

-- 重绘分享按钮
function UICombatStat:redrawShareButton()
    local btnShare = findChildByName(self.node, "BT/btn_share");
    local hintNode = findChildByName(btnShare, "hint");
    local isRemind = false;

    -- 只有主关卡可以分享
    local dungeonId = self.dungeonId;
    if DungeonAreaM.getParentId(dungeonId) ~= dungeonId or
        not DungeonAreaM.isEndlessArea(dungeonId) then
        if not isShareFuncOpen() then
            -- 功能不开放
            setButtonEnabled(btnShare, false);
            btnShare:setVisible(false);
        else
            -- 置灰
            setButtonEnabled(btnShare, false);
            checkBlueBubbleStatus(hintNode, false);
        end
        return;
    end

    if isShareFuncOpen() then
        -- 如果今日都没有分享过，需要提醒
        if ShareM.getTodayShareDungeonTimes() <= 0 then
            isRemind = true;
        end
        setButtonEnabled(btnShare, true);
        btnShare:setVisible(true);
    else
        setButtonEnabled(btnShare, false);
        btnShare:setVisible(false);
    end

    checkBlueBubbleStatus(hintNode, isRemind);
end

-- 注册点击事件
function UICombatStat:registerTouchEvent()
    -- 点击背景快速结算本页，再次点击进入下一个结算
    local bg = findChildByName(self.node, "black_bg");
    bg:addTouchEventListener(function(sender, ev)
        if ev == ccui.TouchEventType.ended then
            self:skipHandler();
        end
    end);

    -- 返回按钮
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            self:closeWindow();
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 分享按钮
    local btnShare = findChildByName(self.node, "BT/btn_share");
    TextStyleM.setTextStyle(btnShare, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnShare:setTitleText(getLocStr("share"));
    local function onShareClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:showShareForm();
        end
    end
    btnShare:addTouchEventListener(onShareClick);
end

-- 初始化组件位置
function UICombatStat:init()
    -- 需要先取物品列表，否则会被DUNGEON_SERIVICE清除
    self:getTreasureList();

    -- 初始化位置在屏幕右侧
    -- 具体条目
    for i = 1, 15 do
        local item = findChildByName(self.node, "CT/group1/item"..i);
        if item ~= nil then
            item:setPositionX(DESIGN_WIDTH);
        end
    end

    -- 经验/金钱
    local nodeNames = {"gold_node", "exp_node", "exp_progress_node"};
    for i = 1, 3 do
        local left = findChildByName(self.node, "BT/"..nodeNames[i].."/left");
        local right = findChildByName(self.node, "BT/"..nodeNames[i].."/right");
        left:setPositionX(DESIGN_WIDTH);
        right:setPositionX(DESIGN_WIDTH);
    end

    -- 总积分
    local totalScoreNode = findChildByName(self.node, "BT/total_score_node");
    totalScoreNode:setPositionX(DESIGN_WIDTH);
end

-- 开始动画效果
function UICombatStat:start()
    self:gotoState(STAT_STATE_TITLE_ANIMA);
end

-- 状态处理
function UICombatStat:gotoState(state)
    self.state = state;
    accelarateFactor = 1;
    self.isWaiting = false;

    local stateTables =
        {
            [STAT_STATE_TITLE_ANIMA] = UICombatStat.doBackgroudAnimation,
            [STAT_STATE_SCORE_ANIM] = UICombatStat.doScoreAnimation,
            [STAT_STATE_GROUP1_ANIM] = UICombatStat.doGroup1Animation,
            [STAT_STATE_GROUP4_ANIM] = UICombatStat.doGroup4Animation,
            [STAT_STATE_EXP_ANIM] = UICombatStat.loadingBarAction,
            [STAT_STATE_END] = function() end,
        };

    if stateTables[self.state] ~= nil then
        stateTables[self.state](self);
    end

    if state == STAT_STATE_END then
        -- 重新显示物品/评分信息
        if self.ct ~= nil then
            removeLevelUpEffect(self.ct);
        end
        local items = self:getAllGainTreasure();
        if #items ~= 0 then
            local panel = findChildByName(self.node, "CT/panel/items");
            panel:setVisible(true);
            panel:setTouchEnabled(true);
        else
            local group1 = findChildByName(self.node, "CT/group1");
            group1:setVisible(true);
        end
    end
end

-- 等待下一步操作
function UICombatStat:waitingForNextStep()
    print("state:".. self.state.." waitingForNextStep");
    local function timeout()
        if self.state < STAT_STATE_END then
            self:gotoState(self.state + 1);
        end
    end

    performWithDelay(self, timeout, waitingTime)

    self.isWaiting = true;
end

-- 关闭界面
function UICombatStat:closeWindow()
    -- -- 由于升级动画会被跳过,这里确保等级经验值是正确的
    -- ME.user.dbase:set("level", self.finalLevel);
    -- ME.user.dbase:set("exp", self.finalExp);

    -- 删除记录值
    ME.user.oriExpInfo = nil;

    -- 抛出事件
    EventMgr.fire(event.USER_EXP_UP);

    -- 清除当前窗口，回到指定的界面
    self:goToDesignatedForm();

    -- 清除地牢数据
    UIDungeonMgr.clearCurLevel();

    UIMgr.tryClearUnusedTextures();
end

-- 回到指定的界面
function UICombatStat:goToDesignatedForm()
    -- 保留的窗口
    local remainForm;

    -- 如果是从天空副本进入的，那么回到飞艇主界面
    if self.dungeonId and SkyInstanceM.isSkyInstance(self.dungeonId) then
        DungeonM.dungeonType = DUNGEON_TYPE_SKY_INSTANCE;
        remainForm = {"UISkyCity", "UIMainMap", "UIBottomMenu", "UITopMenu"};
        UIMgr.getCurrentScene():removeAllFormWithoutList(remainForm);
        local bgm = AudioM.queryFormAudioInfo("UISkyCity", "open_bgm");
        if bgm ~= nil and bgm ~= "" then
            AudioM.playBgMusic(bgm);
        end
    -- 如果是从天空活动副本进入的，那么回到天空活动主界面
    elseif self.dungeonId and ActivityDungeonM.isActivityDungeon(self.dungeonId) then
        local activityId = ActivityDungeonM.getActivityByDungeonId(self.dungeonId)["id"];

        if ActivityM.query(activityId, "rule") == "sky_activity" then
            DungeonM.dungeonType = DUNGEON_TYPE_SKY_ACTIVITY_INSTANCE;
            DungeonM.SkyActivityId = activityId;
            remainForm = {"UISkyActivity", "UISkyCity", "UIMainMap", "UIBottomMenu", "UITopMenu"};
            UIMgr.getCurrentScene():removeAllFormWithoutList(remainForm);
            local bgm = AudioM.queryFormAudioInfo("UISkyActivity", "open_bgm");
            if bgm ~= nil and bgm ~= "" then
                AudioM.playBgMusic(bgm);
            end
        else
            -- 关闭除了主界面的所有界面
            remainForm = {"UIMainMap", "UIBottomMenu", "UITopMenu"};
            UIMgr.getCurrentScene():removeAllFormWithoutList(remainForm);
            local bgm = AudioM.queryFormAudioInfo("UIMainMap", "open_bgm");
            if bgm ~= nil and bgm ~= "" then
                AudioM.playBgMusic(bgm);
            end
        end
    -- 如果是觉醒试炼地牢，那么回到觉醒试炼地牢列表界面
    elseif self.dungeonId and AwakeM.isAwakeDungeon(self.dungeonId) then
        DungeonM.dungeonType = DUNGEON_TYPE_AWAKE;
        remainForm = {"UIAwakeMain", "UIHeroMain", "UIHeroMain", "UIMainMap", "UIBottomMenu", "UITopMenu"};
        UIMgr.getCurrentScene():removeAllFormWithoutList(remainForm);
        local bgm = AudioM.queryFormAudioInfo("UIAwakeMain", "open_bgm");
        if bgm ~= nil and bgm ~= "" then
            AudioM.playBgMusic(bgm);
        end
    -- 否则回到世界地图
    else
        -- 关闭除了主界面的所有界面
        remainForm = {"UIMainMap", "UIBottomMenu", "UITopMenu"};
        UIMgr.getCurrentScene():removeAllFormWithoutList(remainForm);
        local bgm = AudioM.queryFormAudioInfo("UIMainMap", "open_bgm");
        if bgm ~= nil and bgm ~= "" then
            AudioM.playBgMusic(bgm);
        end
   end
end

-- 快速略过处理
function UICombatStat:skipHandler()
    print("state:"..self.state..", isWaiting:"..tostring(self.isWaiting));

    if self.isWaiting then
        self:stopAllActions();
        if self.state <= STAT_STATE_EXP_ANIM then
            self:gotoState(self.state + 1);
        end
        self.isWaiting = false;
        return;
    end

    if self.state <= STAT_STATE_TITLE_ANIMA then
        return
    end

    if self.state <= STAT_STATE_SCORE_ANIM then
        self:showScoreRightNow();
    elseif self.state <= STAT_STATE_GROUP1_ANIM then
        self:showGroup1RightNow();
    elseif self.state <= STAT_STATE_GROUP4_ANIM then
        self:showGroup4RightNow();
        accelarateFactor = 1.3;
    elseif self.state <= STAT_STATE_EXP_ANIM then
        if self.playingLevelUpEffect then
            -- 正在播放动画
            local function doneEffect()
                self.playingLevelUpEffect = false;
                self.waitUserClick = true;
            end
            -- 略过动画
            playLevelUpEffect(self.ct, self.curLevel, doneEffect, true);
        elseif self.waitUserClick then
            -- 播完动画了
            self.waitUserClick = false;
        end
    end
end

-- 标题动画
function UICombatStat:titleAnimation(callback)
    -- 标题先放大后缩小再放大
    local titleNode = findChildByName(self.node, "TOP/title_node");
    titleNode:setScale(1.5);

    local scaleDown = cc.ScaleTo:create(0.5, 0.9);
    local scaleUp = cc.ScaleTo:create(0.5, 1.0);
    local gotoNextState = cc.CallFunc:create(function ()
        if callback ~= nil then
            callback();
        end
    end);
    AudioM.playFx("pop_score");
    titleNode:runAction(cc.Sequence:create(scaleDown, scaleUp, gotoNextState));
end

-- 背景动画
function UICombatStat:doBackgroudAnimation()
    -- 背景圆圈滚动
    local ctBg = findChildByName(self.node, "CT/ct_bg");
    ctBg:setScale(0.3);
    local scaleUp = cc.ScaleTo:create(0.5, 1.0);
    local callback = cc.CallFunc:create(function ()
        local rotateForever = cc.RepeatForever:create(cc.RotateBy:create(30, 360));
        ctBg:runAction(rotateForever);
    end);

    ctBg:runAction(cc.Sequence:create(scaleUp, callback));

    local function callback()
        -- 开始第一组评分动画
        self:gotoState(STAT_STATE_SCORE_ANIM);
    end

    self:titleAnimation(callback);
end


-- 总动画
function UICombatStat:doScoreAnimation()
    self:gotoState(STAT_STATE_GROUP1_ANIM);
end

-- 下面总评分动画先飞入
function UICombatStat:showTotalScore()
    -- 节点名
    local nodeNames = {"gold_node", "exp_node", "exp_progress_node"};

    -- 下面三行从左右分别飞入
    local callback = cc.CallFunc:create(function ()
        local i = 1;
        local delay = 0.2;
        local function flyIn()
            local left = findChildByName(self.node, "BT/"..nodeNames[i].."/left");
            local right = findChildByName(self.node, "BT/"..nodeNames[i].."/right");
            local move1 = cc.MoveTo:create(textDuration, cc.p(0, left:getPositionY()));
            local move2 = cc.MoveTo:create(textDuration, cc.p(0, left:getPositionY()));

            left:runAction(move1);
            right:runAction(move2);

            i = i + 1;
            if i <= 3 then
                performWithDelay(self, flyIn, delay);
            else
                -- 显示分数
                local score = self.combatStat.score1 + self.combatStat.score2 + self.combatStat.score3 + self.combatStat.score4;
                self:updateScore(score);
            end

            -- 播放飞入音效
            AudioM.playFx("stat_fly_in");
        end

        flyIn();
    end);

    -- 总积分先飞入
    local totalScoreNode = findChildByName(self.node, "BT/total_score_node");
    local move = cc.MoveTo:create(textDuration, cc.p(0, totalScoreNode:getPositionY()));
    totalScoreNode:runAction(cc.Sequence:create(move, callback));
end

-- 总评分立即显示
function UICombatStat:showTotalScoreRightNow()
    self:stopAllActions();
    local totalScoreNode = findChildByName(self.node, "BT/total_score_node");
    totalScoreNode:stopAllActions();
    totalScoreNode:setPositionX(0);

    local nodeNames = {"gold_node", "exp_node", "exp_progress_node"};
    for i = 1, 3 do
        local left = findChildByName(self.node, "BT/"..nodeNames[i].."/left");
        left:stopAllActions();
        left:setPositionX(0);

        local right = findChildByName(self.node, "BT/"..nodeNames[i].."/right");
        right:stopAllActions();
        right:setPositionX(0);
    end

    self:waitingForNextStep();
end

-- 计算积分与金币经验
function UICombatStat:updateScore(score)
    -- 分值滚动
    local scoreSumLabel = findChildByName(self.node, "BT/total_score_node/score_sum");
    scoreScrolling(scoreSumLabel, score, nil, 50);

    local curMoney = math.floor(score * self.totalMoney / self.combatStat.sum);
    local curExp = math.floor(score * self.totalExp / self.combatStat.sum);

    -- 金钱奖励
    local goldAddMark = findChildByName(self.node, "BT/gold_node/right/gold_add_mark");
    goldAddMark:setVisible(false);
    local goldAddLabel = findChildByName(self.node, "BT/gold_node/right/gold_add_value");
    goldAddLabel:setVisible(false);

    -- 经验奖励
    local expAddMark = findChildByName(self.node, "BT/exp_node/right/exp_add_mark");
    expAddMark:setVisible(false);
    local expAddLabel = findChildByName(self.node, "BT/exp_node/right/exp_add_value");
    expAddLabel:setVisible(false);
end

-- 奖励动画
function UICombatStat:doBonusAnimation()
    local group1 = findChildByName(self.node, "CT/group1");

    -- 金币，经验值动画
    -- 金钱奖励
    local goldLabel = findChildByName(self.node, "BT/gold_node/right/gold_value");
    TextStyleM.setTextStyle(goldLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE);
    scoreScrolling(goldLabel, self.totalMoney, nil, 20);

    local goldAddLabel = findChildByName(self.node, "BT/gold_node/right/gold_add_value");
    local goldAddMark = findChildByName(self.node, "BT/gold_node/right/gold_add_mark");
    goldAddLabel:setVisible(true);
    goldAddMark:setVisible(true);
    TextStyleM.setTextStyle(goldAddLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_YELLOW);
    TextStyleM.setTextStyle(goldAddMark, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_YELLOW);
    goldAddMark:setString("+");
    goldAddLabel:setString("0");
    scoreScrolling2(goldAddLabel, 0, nil, 20);

    -- 经验奖励
    local expLabel = findChildByName(self.node, "BT/exp_node/right/exp_value");
    TextStyleM.setTextStyle(expLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BEIGE);
    scoreScrolling(expLabel, self.totalExp, nil, 20);

    local expAddLabel = findChildByName(self.node, "BT/exp_node/right/exp_add_value");
    local expAddMark = findChildByName(self.node, "BT/exp_node/right/exp_add_mark");
    TextStyleM.setTextStyle(expAddLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_YELLOW);
    TextStyleM.setTextStyle(expAddMark, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_LIGHT_YELLOW);
    expAddLabel:setVisible(true);
    expAddMark:setVisible(true);
    expAddMark:setString("+");
    expAddLabel:setString("0");
    scoreScrolling2(expAddLabel, 0, nil, 20);
    -- 播放数值滚动音效
    AudioM.playFx("stat_scrolling");
end

-- 经验条动画
function UICombatStat:loadingBarAction()
    -- 去掉物品
    local panel = findChildByName(self.node, "CT/panel/items");
    local group1 = findChildByName(self.node, "CT/group1");

    -- 金币/经验奖励动画
    self:doBonusAnimation();

    -- 经验条动画
    local loadingBar = findChildByName(self.node, "BT/exp_progress_node/right/progress_bg/loading_bar");

    local incCount = 50;
    local incDelta = self.totalExp / incCount;
    local count = 0;
    local nextDelta = 0;

    local function increaseExpBar()
        if self.playingLevelUpEffect or self.waitUserClick then
            performWithDelay(self, increaseExpBar, 0.01);
            return;
        end

        nextDelta = incDelta;
        if self.curExp + incDelta >= self.curMaxExp then
            -- 需要显示升级动画,隐藏panel,隐藏GROUP1
            panel:setVisible(false);
            panel:setTouchEnabled(false);
            group1:setVisible(false);

            nextDelta = incDelta - (self.curMaxExp - self.curExp);
            -- 升级需要等待玩家确认
            self.waitUserClick = true;

            self.curExp = 0;
            self.curLevel = self.curLevel + 1;
            self.curMaxExp = UserM.queryWorldTree(self.curLevel, "exp");

            -- 显示升级动画
            print("升级啦 level:"..self.curLevel.."升级奖励经验"..self.totalExp);
            self.playingLevelUpEffect = true;
            self.ct = self.node:getChildByName("CT");
            local function doneEffect()
                self.playingLevelUpEffect = false;
                self.waitUserClick = true;
            end
            loadingBar:setPercent(100);
            playLevelUpEffect(self.ct, self.curLevel, doneEffect, false);
        end

        self.curExp = self.curExp + nextDelta;

        if not self.playingLevelUpEffect then
            local percent = self.curExp / self.curMaxExp * 100;
            loadingBar:setPercent(percent);
        end

        count = count + 1;
        if count >= incCount and not self.playingLevelUpEffect then
            self:waitingForNextStep();
        else
            performWithDelay(self, increaseExpBar, 0.01);
        end
    end

    increaseExpBar();
end

-- 评分立即显示
function UICombatStat:showScoreRightNow()
    if self.showScoreDone then
        self:gotoState(self.state + 1);
        self:stopAllActions();
        return;
    end

    self:stopAllActions();
    self.showScoreDone = true;
    -- 自动进入下一个动画
    local function autoNext()
        self:gotoState(self.state + 1);
    end
    performWithDelay(self, autoNext, waitingTime);
end

-- 第一组数据飞入
function UICombatStat:doGroup1Animation()
    local i = 1;
    local function flyIn()
        if i > 15 then
            -- 飞入总评分
            self:showTotalScore();
            self:waitingForNextStep();
            accelarateFactor = 1;
            return;
        end

        local item = findChildByName(self.node, "CT/group1/item"..i);

        if item == nil then
            -- 没有的直接略过
            i = i + 1;
            flyIn();
            return;
        end

        local y = item:getPositionY();

        local moveToCenter = cc.MoveTo:create(textDuration, cc.p(0, y));
        local callback = cc.CallFunc:create(function ()
            -- 分数跳动
            local score = item:getChildByName("score");
            local val = tonumber(score:getString());
            local function nextLine()
                -- 下一行数字飞入
                i = i + 1;
                flyIn();
            end
            scoreScrolling(score, val, nextLine, 200);
        end);

        item:runAction(cc.Sequence:create(moveToCenter, callback));

        -- 播放飞入音效
        AudioM.playFx("stat_fly_in");
    end

    flyIn();
end

-- 第一组数据立即显示
function UICombatStat:showGroup1RightNow()
    if self.showGroup1Done then
        self:stopAllActions();
        self:gotoState(self.state + 1);
        return;
    end

    local group1 = findChildByName(self.node, "CT/group1");
    group1:setVisible(false);

    local titleNode = findChildByName(self.node, "TOP/title_node");
    titleNode:setScale(1.0);
    titleNode:stopAllActions();

    self:stopAllActions();

    -- 停止当前所有动作, 直接到目标位置
    for i = 1, 15 do
        local item = findChildByName(self.node, "CT/group1/item"..i);
        if item ~= nil then
            local score = item:getChildByName("score");
            score:stopAllActions();
            score:setString(tostring(score.statData));
            item:stopAllActions();
            item:setPositionX(0);
        end
    end

    -- 显示分数
    local score = self.combatStat.score1 + self.combatStat.score2 + self.combatStat.score3 + self.combatStat.score4;
    self:showTotalScoreRightNow();
    self:updateScore(score);

    group1:setVisible(true);

    self.state = STAT_STATE_GROUP1_ANIM;
    self.showGroup1Done = true;

    self:waitingForNextStep();
end

-- panel最初位置
local panelY;

-- 物品飞入
function UICombatStat:itemsFlyIn(items, callback)
    local group1 = findChildByName(self.node, "CT/group1");
    group1:setVisible(false);

    local panel = findChildByName(self.node, "CT/panel/items");
    panel:removeAllChildren();
    panelY = panel:getPosition();

    -- 飞入物品，不可拖动
    panel:setTouchEnabled(false);

    self.itemFlyFinish = false;

    if #items == 0 then
        if callback ~= nil then
            self.itemFlyFinish = true;
            callback();
        end
        return;
    end

    local itemWidth = 140;
    local leftMargin = 25;
    local hGap = 8.5;
    local vGap = 0;

    -- 设置容易高度
    local addLine = math.ceil(#items / 4) - 3;
    if addLine < 0 then
        addLine = 0;
    end

    -- 初始化位置
    for i = 1, #items do
        local item = items[i];
        local y = 420 - (math.floor((i-1) / 4) - addLine) * (itemWidth+vGap) - (itemWidth/2+vGap);
        panel:addChild(item);
        item:setPosition(cc.p(900, y));
    end

    if addLine > 0 then
        local totalHeight = 410 + (itemWidth+vGap) * addLine;
        panel:setInnerContainerSize(cc.size(panel:getInnerContainerSize().width, totalHeight));
        panel:scrollToTop(0.01, true);
    end

    local flyIn;
    local i = 1;
    local delayCount = 1;
    local capacity = 12;
    local alreadyAddLine = 1;

    -- 整个panel往上挪
    local function movePanelUp()
        local moveTo = cc.MoveTo:create(0.25 / accelarateFactor, cc.p(panel:getPositionX(), panel:getPositionY() + (itemWidth+vGap)));
        local callback = cc.CallFunc:create(function()
            capacity = capacity + 4;
            delayCount = 1;
            -- 继续飞入其他的item
            flyIn();
        end);

        local delay = cc.DelayTime:create(0.25);
        local totalHeight = panel:getInnerContainerSize().height;
        -- 计算上移的百分比
        local percent = alreadyAddLine / addLine * 100;
        -- 增加已经上移的次数
        alreadyAddLine = alreadyAddLine + 1;
        panel:scrollToPercentVertical(percent, 0.25, true);
        self:runAction(cc.Sequence:create(delay, callback));
    end

    local count = 0;

    -- 依次飞入
    flyIn = function()
        if i > capacity then
            -- 超过可显示个数，暂停，等panel上移后继续
            return;
        end

        if i > #items then
            return;
        end

        -- 物品飞入速度
        local speed = 2050 * accelarateFactor;

        local item = items[i];
        local delay = cc.DelayTime:create(delayCount * 0.1 / accelarateFactor);
        local x = leftMargin + itemWidth/2 + ((i-1)%4)*(itemWidth+hGap);
        local moveTo = cc.MoveTo:create((900-x)/speed, cc.p(x, item:getPositionY()));
        local callback = cc.CallFunc:create(function()
            count = count + 1;
            if count >= 12 and (count % 4) == 0 then
                if count ~= #items then
                    movePanelUp();
                end
            end

            if count >= #items then
                -- 播放完成
                self.itemFlyFinish = true;
                -- 可以拖动
                panel:setTouchEnabled(true);
                self:waitingForNextStep();
            end
        end);

        item:runAction(cc.Sequence:create(delay, moveTo, callback));

        -- 播放飞入音效
        AudioM.playFx("stat_fly_in");

        i = i + 1;
        delayCount = delayCount + 1;
        performWithDelay(self, flyIn, 0.1 / accelarateFactor);
    end

    flyIn();
end

-- 立刻显示物品
function UICombatStat:showItemsRightNow(items)
    if self.itemFlyFinish then
        return;
    end
    -- 隐藏
    local group1 = findChildByName(self.node, "CT/group1");
    group1:setVisible(false);

    self:stopAllActions();

    -- 停止当前所有动作, 直接到目标位置
    local panel = findChildByName(self.node, "CT/panel/items");
    local children = panel:getChildren();
    local len = table.getn(children)

    -- 重置panel位置
    if panelY ~= nil then
        panel:setPosition(panel:getPositionX(), panelY);
        panel:setTouchEnabled(false);
    end

    -- 飞入物品，不可拖动
    panel:setTouchEnabled(false);

    for i = 1, len do
        local child = children[i];
        child:stopAllActions();
    end
    panel:removeAllChildren();

    local itemWidth = 140;
    local leftMargin = 25;
    local hGap = 8.5;
    local vGap = 0;

    local num = #items;

    -- 设置容器高度
    local addLine = math.ceil(#items / 4) - 3;

    if addLine < 0 then
        addLine = 0;
    end

    if addLine > 0 then
        local totalHeight = 410 + (itemWidth+vGap) * addLine;
        panel:setInnerContainerSize(cc.size(panel:getInnerContainerSize().width, totalHeight));
        panel:scrollToTop(0.01, true);
    end

    -- 设置物品位置
    for i = 1, num do
        local item = items[i];
        local x = leftMargin + itemWidth/2 + ((i-1)%4)*(itemWidth+hGap);
        local y = 420 - (math.floor((i-1) / 4) - addLine) * (itemWidth+vGap) - (itemWidth/2+vGap);
        item:setPosition(x, y);
        panel:addChild(item);
    end

    -- 容器直接置到最底
    panel:jumpToBottom();

    panel:setTouchEnabled(true);
end

-- 玩家宝物列表ID
function UICombatStat:getTreasureList()
    self.treasureList = table.keys(ME.user.dbase:query("take_out_item", {}))
    self.AllItem = ME.user.dbase:query("take_out_item");
end

-- 宝物列表
function UICombatStat:getAllGainTreasure()
    local combatItem = cc.CSLoader:createNode("layout/combat_stat/CombatStatItem.csb");
    local widget = replaceNodeWithWidget(combatItem);

    local items = {};

    local bonusList = self.combatStat.bonus;

     for _, arr in pairs(bonusList) do
        if arr[1] == 2 and arr[2] == "gem" then

            local child = widget:clone();

            -- 获取物品图标
            local iconIndex = FieldsM.query(arr[2], "icon");
            local icon = child:getChildByName("icon");
            icon:loadTexture(getLargeAttribIconPath(iconIndex));

            -- 物品奖励
            local amount = arr[3];

            local kerning = -2;
            -- 数量
            local num  = child:getChildByName("num");
            TextStyleM.setTextStyle(num, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
            num:setString(tostring(amount));
            num:setFontSize(TextStyleM.TEXT_SIZE_SMALL);

            -- 点击处理
            local bg = findChildByName(child, "bg");
            bg:addTouchEventListener(function(sender, eventType)
                if eventType == ccui.TouchEventType.ended then
                    showBonusDesc(arr);
                end
            end);

            table.insert(items, child);
        end
    end

    if #self.treasureList <= 0 then
        return items;
    end

    local function sortItem(classId1, classId2)
        if classId1 < classId2 then
            return true;
        end
        return false;
    end
    -- 排序
    table.sort(self.treasureList, sortItem);

    for _, classId in pairs(self.treasureList) do
        -- 获取宝物图标
        local iconIndex = ItemM.query(classId, "icon");
        -- 数量
        local count = self.AllItem[classId];

        -- 星星
        local rank = ItemM.query(classId, "rank");

        local item = widget:clone();
        local icon = item:getChildByName("icon");
        local num  = item:getChildByName("num");
        local star = item:getChildByName("star");
        icon:loadTexture(getItemIconPath(iconIndex));
        num:setString(tostring(count));

        -- 显示星星
        local tStar = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
        if tStar ~= nil then
            star:addChild(tStar);
        end

        -- 点击处理
        local bg = findChildByName(item, "bg");
        bg:addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("workshop_material");
                -- 显示道具详细信息
                local groupList = {24,};
                local itemGroup = ItemM.query(classId, "group")
                if table.indexOf(groupList, itemGroup) ~= -1 then
                    -- 特殊物品
                    local uiPropertyInfo = UIPropertyInfo.create(classId);
                    UIMgr.getCurrentScene():addForm(uiPropertyInfo);
                else
                    showBonusDesc({1, classId, 1});
                end
            end
        end);

        local kerning = -2;

        TextStyleM.setTextStyle(num, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
        num:setFontSize(TextStyleM.TEXT_SIZE_SMALL);
        table.insert(items, item);
    end

    return items;
end

-- 宝物评分动画
function UICombatStat:doGroup4Animation()
    local items = self:getAllGainTreasure();

    function callback()
        -- 统计结束
        self:waitingForNextStep();
    end

    if #items ~= 0 then
        -- 标题动画
        local formTitleLabel = findChildByName(self.node, "TOP/title_node/title");
        formTitleLabel:setString(getLocStr("spoils"));
        TextStyleM.setArtWordTitleStyle(formTitleLabel);

        self:titleAnimation();

        -- 飞入动画
        self:itemsFlyIn(items);

    else
        -- 没有物品直接进入经验结算
        self:gotoState(self.state + 1);
    end
end

-- 技能评分立即显示
function UICombatStat:showGroup4RightNow()
    local items = self:getAllGainTreasure();

    if self.showGroup4Done or #items == 0 then
        -- 没有物品直接进入经验结算
        self:gotoState(self.state + 1);
        self:waitingForNextStep();
        return;
    end

    -- 显示物品
    self:showItemsRightNow(items);

    self.showGroup4Done = true;
    self:waitingForNextStep();
end


